package br.com.bcc481.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.bcc481.models.Usuario;

public class HibernateUsuarioDAO {
	
	
	public static void addUsuario(Usuario usuario) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager em = factory.createEntityManager();

		em.getTransaction().begin();    
		em.persist(usuario);
		em.getTransaction().commit();

		em.close();

		factory.close();
	}


	public static Usuario pesquisaUsuarioPorId(Long chave) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager manager = factory.createEntityManager();

		//cuidado, use o import javax.persistence.Query
		Query query = manager.createQuery("from Usuario where id = "+ "'" + chave + "'");

		List<Usuario> lista = query.getResultList();

		if (lista.size() > 0) {
			manager.close();
			return lista.get(0);
		}
		else
			return null;

	}
	
	
	public static Usuario pesquisaUsuarioPorEmail(String chave) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager manager = factory.createEntityManager();

		//cuidado, use o import javax.persistence.Query
		Query query = manager.createQuery("from Usuario where email = " + "'" + chave + "'");

		List<Usuario> lista = (List<Usuario>) query.getResultList();
		
		if (lista.size() > 0) {
			manager.close();
			return lista.get(0);
		}
		else
			return null;

	}

	public static int removeUsuario(Long chave) {

		Usuario usuario = new Usuario();
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager em = factory.createEntityManager();

		usuario = pesquisaUsuarioPorId(chave);

		//CASO ENCONTRE ALGUM CONTATO, DELETA DO BANCO
		if (usuario != null) {

			em.getTransaction().begin();
			Object c = em.merge(usuario);
			em.remove(c);
			em.getTransaction().commit();
			em.close();
			
			return 1;
		}
		else {
			return 0;
		}
		
	}
	
	public static int atualizaUsuario(Usuario usuario) {
		
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager em = factory.createEntityManager();

		em.getTransaction().begin();
		em.merge(usuario);
		em.getTransaction().commit();
		
		return 1;
	}

}
